from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Crop_Data_Processing_schema
from controller import Crop_Data_Processing_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Crop_Data_Processing", response_model=Crop_Data_Processing_schema.Crop_data_processing, tags=["Crop_Data_Processing"])
async def create_Crop_Data_Processing(Crop_Data_Processing: Crop_Data_Processing_schema.Crop_data_processing, db: Session = Depends(get_db)):
    return Crop_Data_Processing_controller.create_Crop_Data_Processing(db, Crop_Data_Processing)


@router.get("/Crop_Data_Processing/{ID}", response_model=Crop_Data_Processing_schema.Crop_data_processing, tags=["Crop_Data_Processing"])
async def get_Crop_Data_Processing(ID: int, db: Session = Depends(get_db)):
    db_Crop_Data_Processing = Crop_Data_Processing_controller.get_Crop_Data_Processing(db, ID)
    if db_Crop_Data_Processing is None:
        raise HTTPException(status_code=404, detail="Crop_Data_Processing not found")
    return db_Crop_Data_Processing


@router.get("/Crop_Data_Processing", response_model=List[Crop_Data_Processing_schema.Crop_data_processing], tags=["Crop_Data_Processing"])
async def get_all_Crop_Data_Processing(db: Session = Depends(get_db)):
    all_db_Crop_Data_Processing = Crop_Data_Processing_controller.get_all_Crop_Data_Processing(db)
    if all_db_Crop_Data_Processing is None:
        raise HTTPException(status_code=404, detail="0 Crop_Data_Processing found, empty table")
    return all_db_Crop_Data_Processing


@router.put("/Crop_Data_Processing/{ID}", tags=["Crop_Data_Processing"])
async def update_Crop_Data_Processing(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Crop_Data_Processing = Crop_Data_Processing_controller.update_Crop_Data_Processing(db, ID, field_name, field_value)
        if db_Crop_Data_Processing is None:
            raise HTTPException(status_code=404, detail="Crop_Data_Processing not found")
        return db_Crop_Data_Processing
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Crop_Data_Processing/{ID}", tags=["Crop_Data_Processing"])
async def delete_Crop_Data_Processing(ID: int, db: Session = Depends(get_db)):
    is_deleted = Crop_Data_Processing_controller.delete_Crop_Data_Processing(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
